import {ActionType, ProColumns, ProTable} from "@ant-design/pro-components";
import React, {MutableRefObject, useEffect, useState} from "react";
import {pageDictType} from "@/pages/system/dict/api";
import {API} from "@/services/typings";

interface IDictTypeTable {
  name?: string,
  selectRowChange: (row: API.IDictType) => void,
  actionRef: MutableRefObject<ActionType>
}

const DictTypeTable: React.FC<IDictTypeTable> = ({name, selectRowChange, actionRef}) => {
  const [selectedRowId, setSelectedRowId] = useState<string | number | null>(null);

  useEffect(() => {
    actionRef.current?.reload()
  }, [name])

  const columns: ProColumns<any>[] = [
    {
      title: '名称',
      dataIndex: 'dictName',
      ellipsis: true,
      key: 'dictName',
    },
    {
      title: '类型',
      dataIndex: 'dictType',
      ellipsis: true,
      key: 'dictType',
      hideInSearch: true,
      copyable: true,
    },
  ]

  return (
    <ProTable<API.IDictType, API.PageParams>
      actionRef={actionRef}
      rowKey="id"
      search={false}
      toolBarRender={false}
      rowClassName={(record: any) => {
        return record.id === selectedRowId ? 'highlight-row' : '';
      }}
      onRow={(record: any) => {
        return {
          onClick: () => {
            setSelectedRowId(record.id);
            selectRowChange(record)
          },
        };
      }}
      pagination={{
        pageSize: 15,
      } as any}
      request={async (params, sort, filter) => {
        const {data} = await pageDictType({...params, dictName: name})
        if (data) {
          const {data: dictTypeList} = data
          setSelectedRowId(dictTypeList[0].id)
          selectRowChange(dictTypeList[0])
        } else {
          setSelectedRowId(null)
        }
        return data
      }}
      columns={columns}
    />
  )
};
export default DictTypeTable;
